/* eslint-disable @typescript-eslint/no-var-requires */
import React, { useEffect, useState } from 'react';
import { Toast } from 'antd-mobile-v2';
import styles from './index.module.less';
import ApproveCard from '@/components/card';
import { OperationMyTask } from '@/services/index';
import ConfirmAndRefuseModal from '@/components/ConfirmAndRefuseModal';
import history from '@/utils/history';
import { applyType } from '@/constants';
import {
  isCheckedAuth,
  sendVerificationCode,
  checkVerificationCode
} from '@/services/commons';
import VerificationCodeModal from '@/components/verification-code-modal';

interface Props {
  title: string;
  emptyData: string;
  hasButton?: boolean;
  withStatus?: boolean;
  requestList: Function;
  [propsname: string]: any;
}
interface DetailItem {
  innerProcDefId: string;
  applyName: string;
  procRecordId: string;
  applyId: string;
  applyType: string;
  applyUserId: string;
  crtTime: string;
  id: string;
  handler: string;
  procStatus: number;
  needSign: 0 | 1;
}

enum PageListParams {
  PAGE = 1,
  LIMIT = 10,
}

enum OperationsObj {
  CONFIRM = '0004',
  REFUSE = '0007',
}

const TodoList: React.FC<Props> = (props) => {
  const { title, emptyData, hasButton, withStatus, requestList, isMyApply } =
    props;
  const [dataList, setDataList] = useState<any[]>([]);
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [modalObj, setModalObj] = useState<any>({});
  const [type] = useState(1); // 默认为1，1 待审批 2 已审批
  const [loading, setLoading] = useState(false);
  const [verificationCodeModalVisible, setVerificationCodeModalVisible] =
    useState<boolean>(false); // 短信验证弹窗显隐

  //获取列表数据
  const getList = async (page: number) => {
    setLoading(true);
    const data = {
      pageNum: page,
      pageSize: PageListParams.LIMIT,
      operationType: hasButton ? 1 : ''
    };
    try {
      const res = await requestList(data);
      if (res.status === 200) {
        const rows = res.data?.list || [];
        const resList = rows?.slice(0, 5);
        const list = formatData(resList);
        setDataList(list ?? []);
      }
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    getList(1);
  }, []);

  const formatData = (data: any[]): any => {
    data?.forEach((item) => {
      const formValues = item.formValues || item?.formData?.formValues;
      const jsonData = JSON.parse(formValues);
      switch (item.applyType) {
        case applyType.STOCK_RECEIVE_APPLY:
          item.formData = [
            { label: '划转批次', value: jsonData.lot?.text || '无' },
            {
              label: '业务名称',
              value: item.typeName || item.taskName || '无'
            },
            {
              label: '更新时间',
              value: item?.lastHandlerTime || item.crtTime || '无'
            }
          ];
          break;
        default:
          break;
      }
      item.cardTitle = item.applyName || item.procName || '无';
    });
    return data;
  };

  //操作同意
  const handleOK = (item: DetailItem) => {
    confirmHandle('0004', item);
  };

  //操作拒绝
  const handleRefuse = (item: DetailItem) => {
    confirmHandle('0007', item);
  };

  //弹框确认
  const modalOk = async (formVal: string, show: boolean) => {
    const params = {
      action: modalObj?.opreationType,
      taskRecordId: modalObj?.detailItem?.id as string,
      handlerComment: formVal
    };
    try {
      const res = await OperationMyTask(params);
      if (res.status == 200) {
        Toast.success('操作成功');
        setModalVisible(show);
        hasButton && getList(1);
      } else {
        Toast.success(res.message);
      }
    } catch (error) {
      console.log(error);
    }
  };

  const confirmHandle = async (type: string, item: DetailItem) => {
    const needMessageCheck = await checkMessageAuth(item.needSign);
    if (needMessageCheck) {
      setVerificationCodeModalVisible(true);
    }
    if (type === OperationsObj.CONFIRM) {
      setModalObj({
        btnWord: '确认同意',
        opreationTitle: `确定同意${item?.applyName}${
          item?.applyName.includes('申请') ? '吗？' : '申请吗？'
        }`,
        placeholder: '请输入审批意见（必填）',
        opreationType: type,
        detailItem: item
      });
    } else {
      setModalObj({
        btnWord: '确认拒绝',
        opreationTitle: `确定拒绝${item?.applyName}${
          item?.applyName.includes('申请') ? '吗？' : '申请吗？'
        }`,
        placeholder: '请输入审批意见（必填）',
        opreationType: type,
        detailItem: item
      });
    }
    setModalVisible(true);
  };

  const checkMessageAuth = async (needSign: 0 | 1) => {
    // mock
    // needSign = 1;
    // mock end
    if (!needSign) return false;
    const res = await isCheckedAuth();
    if (!res.data) {
      return true;
    }
    return false;
  };

  const doClose = (val: boolean) => {
    setModalVisible(val);
  };

  const doSubmit = (val: boolean, word: string) => {
    // if (modalObj?.opreationType === OperationsObj.REFUSE && !val) {
    //   Toast.fail('请填写拒绝理由');
    //   return false;
    // }
    modalOk(word, val);
  };

  const lookMore = () => {
    if (hasButton) {
      props.history.push('/personal-center/my-declare');
    } else {
      props.history.push('/personal-center/my-create?isMyApply=1');
    }
  };

  const modalProps = {
    topTitle: '审批意见',
    modalVisible,
    doClose,
    doSubmit,
    ...modalObj
  };

  // 跳转去详情页
  const handleJump2Detail = (item: any) => {
    console.log('item:', item);
    history.push({
      pathname: '/declare/detail',
      query: {
        isMyApply: isMyApply ? '1' : '',
        innerProcDefId: item.innerProcDefId,
        procRecordId: item.procRecordId,
        applyId: item.applyId || item.taskRecordId,
        applyType: item.applyType,
        // resubmit: item.status !== APPROVAL_STATUS.Draft ? true : false,
        status: item.procStatus,
        title: item.applyName,
        type: hasButton ? type : undefined,
        taskRecordId: item.taskRecordId,
        needSign: item.needSign
      }
    });
  };

  const handleVerificationClose = () => {
    setVerificationCodeModalVisible(false);
    setModalVisible(false);
  };

  const handleVerifiSuccess = () => {
    setVerificationCodeModalVisible(false);
  };

  return (
    <div className={styles['container']}>
      <div className={styles['content']}>
        <div className={styles['content-title']}>
          <span className={styles['content-title-text']}>{title}</span>
          {dataList.length > 3 && (
            <span className={styles['content-title-all']} onClick={lookMore}>
              查看全部
            </span>
          )}
        </div>
        <div className={styles['content-list']}>
          {loading ? (
            <div className={styles['empty-data']}>
              <i className="iconfont iconjiazai" />
            </div>
          ) : dataList.length > 0 ? (
            dataList.map((item, index) => (
              <div
                className={index < dataList.length - 1 ? 'with-border' : ''}
                key={index}
                onClick={() => handleJump2Detail(item)}
              >
                <ApproveCard
                  data={item}
                  hasButton={hasButton}
                  withStatus={withStatus}
                  onPass={handleOK}
                  from={'home'}
                  onReject={handleRefuse}
                >
                </ApproveCard>
              </div>
            ))
          ) : (
            <div className={styles['empty-data']}>{emptyData}</div>
          )}
        </div>
      </div>
      <ConfirmAndRefuseModal {...modalProps} />
      <VerificationCodeModal
        visible={verificationCodeModalVisible}
        handleModalClose={handleVerificationClose}
        sendVerificationCode={sendVerificationCode}
        checkVerificationCode={checkVerificationCode}
        handleSuccess={handleVerifiSuccess}
        title={'身份验证'}
      />
    </div>
  );
};

export default TodoList;
